//
//  ViewController.swift
//  Browser
//
//  Created by Open on 2/11/15.
//  Copyright (c) 2015 open-groupe. All rights reserved.
//

import UIKit
import WebKit


class ViewController: UIViewController ,UITextFieldDelegate, WKNavigationDelegate{

  

    @IBOutlet var urlField: UITextField!
    @IBOutlet var barView: UIView!
    var webView :WKWebView
    
    @IBOutlet var backBtn: UIBarButtonItem!
    
    @IBOutlet var forwardBtn: UIBarButtonItem!
    
    @IBOutlet var reloadBtn: UIBarButtonItem!
    
    @IBOutlet var progressView: UIProgressView!
    
    required init(coder aDecoder: NSCoder) {
       
        self.webView = WKWebView(frame: CGRectZero)
        super.init(coder: aDecoder)
        self.webView.navigationDelegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
//        self.view.addSubview(webView)
        view.insertSubview(webView, belowSubview: progressView)
        webView.setTranslatesAutoresizingMaskIntoConstraints(false)
        let height = NSLayoutConstraint(item: webView, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1.0, constant: -44)
        let width = NSLayoutConstraint(item: webView, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 1.0, constant: 0)
        view.addConstraints([height,width])
        
        backBtn.enabled = false
        forwardBtn.enabled = false
       
        webView.addObserver(self, forKeyPath: "loading", options: .New, context: nil)
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)
        webView.addObserver(self, forKeyPath: "title", options: .New, context: nil)
     }
    
    override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
        if (keyPath == "loading") {
            backBtn.enabled = webView.canGoBack
            forwardBtn.enabled = webView.canGoForward
        }
        if keyPath == "estimatedProgress"
        {
            progressView.hidden = webView.estimatedProgress == 1
            progressView.setProgress(Float(webView.estimatedProgress), animated: true)
        }
        if keyPath == "title"
        {
            title = webView.title
        }
    }
    
    func  webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
        progressView.setProgress(0.0, animated: false)
    }
    
 
    
    func  webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
         if(navigationAction.navigationType == WKNavigationType.LinkActivated && !navigationAction.request.URL.host!.lowercaseString.hasPrefix("www.appcoda.com"))
         {
            UIApplication.sharedApplication().openURL(navigationAction.request.URL)
            decisionHandler(WKNavigationActionPolicy.Cancel)
        }else
         {
            decisionHandler(WKNavigationActionPolicy.Allow)
        }
    }
    
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        let url = NSURL(string: "http://www.appCoda.com")
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        NSLog("view frame is \(NSStringFromCGRect(view.frame))" )
        NSLog("webview frame is \(NSStringFromCGRect(webView.frame))" )
        NSLog("barView frame is \(NSStringFromCGRect(barView.frame))" )
        barView.frame = CGRectMake(0, 0, view.frame.width, 30)

    }
    
    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        barView.frame = CGRect(x: 0, y: 0, width: size.width, height: 30)
        
    }

    //MARK - UITextField Delegate
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        urlField.resignFirstResponder()
        webView.loadRequest(NSURLRequest(URL: NSURL(string: urlField.text)!))
        return false
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        textField.text = "http://"
    }

    @IBAction func back(sender: UIBarButtonItem) {
        webView.goBack()
    }
    
    @IBAction func forward(sender: AnyObject) {
        webView.goForward()
    }
    
    @IBAction func reload(sender: AnyObject) {
//        webView.reload()
        let request = NSURLRequest(URL: webView.URL!)
        webView.loadRequest(request)
    }
    
    func   webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
        let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        presentViewController(alert, animated: true, completion: nil)
    }
}

